<template>
  <div class="user-management">
    <h1>用户管理</h1>
    
    <el-card>
      <template #header>
        <div class="card-header">
          <el-input
            v-model="searchQuery"
            placeholder="搜索用户"
            class="search-input"
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><search /></el-icon>
            </template>
          </el-input>
        </div>
      </template>
      
      <el-table
        :data="filteredUsers"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="realName" label="真实姓名" width="120" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="creditScore" label="信用分" width="100">
          <template #default="scope">
            <el-progress 
              :percentage="scope.row.creditScore" 
              :color="getCreditScoreColor(scope.row.creditScore)" 
            />
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间" width="180" />
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              :type="scope.row.status === 1 ? 'danger' : 'success'" 
              size="small" 
              @click="handleStatusChange(scope.row)"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 编辑用户对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑用户信息"
      width="500px"
    >
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="editForm.realName" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="editForm.phone" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editForm.email" />
        </el-form-item>
        <el-form-item label="信用分">
          <el-slider v-model="editForm.creditScore" :min="0" :max="100" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="editForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="正常"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">确认</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="300px"
    >
      <div class="delete-confirm">
        确定要删除该用户吗？此操作不可恢复！
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
    
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { Search } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

export default {
  name: 'UserManagement',
  components: {
    Search
  },
  setup() {
    const loading = ref(false)
    const users = ref([])
    const searchQuery = ref('')
    const editDialogVisible = ref(false)
    const deleteDialogVisible = ref(false)
    const editForm = ref({})
    const deleteUserId = ref(null)
    
    const filteredUsers = computed(() => {
      if (!searchQuery.value) {
        return users.value
      }
      const query = searchQuery.value.toLowerCase()
      return users.value.filter(user => 
        user.username.toLowerCase().includes(query) ||
        (user.realName && user.realName.toLowerCase().includes(query)) ||
        (user.phone && user.phone.includes(query))
      )
    })
    
    const fetchUsers = async () => {
      loading.value = true
      try {
        const res = await axios.get('/api/admin/users')
        if (res.data.success) {
          users.value = res.data.data
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
        ElMessage.error('获取用户列表失败')
      } finally {
        loading.value = false
      }
    }
    
    const handleSearch = () => {
      // 搜索功能通过computed属性filteredUsers自动实现
    }
    
    const handleEdit = (row) => {
      editForm.value = { ...row }
      editDialogVisible.value = true
    }
    
    const submitEdit = async () => {
      try {
        const res = await axios.put(`/api/admin/users/${editForm.value.id}`, editForm.value)
        if (res.data.success) {
          ElMessage.success('用户信息更新成功')
          fetchUsers()
          editDialogVisible.value = false
        } else {
          ElMessage.error(res.data.message || '更新失败')
        }
      } catch (error) {
        console.error('更新用户信息失败:', error)
        ElMessage.error('更新用户信息失败')
      }
    }
    
    const handleStatusChange = async (row) => {
      const newStatus = row.status === 1 ? 0 : 1
      try {
        const res = await axios.put(`/api/admin/users/${row.id}`, {
          ...row,
          status: newStatus
        })
        if (res.data.success) {
          ElMessage.success(`用户状态已${newStatus === 1 ? '启用' : '禁用'}`)
          fetchUsers()
        } else {
          ElMessage.error(res.data.message || '操作失败')
        }
      } catch (error) {
        console.error('更改用户状态失败:', error)
        ElMessage.error('更改用户状态失败')
      }
    }
    
    const handleDelete = (id) => {
      deleteUserId.value = id
      deleteDialogVisible.value = true
    }
    
    const confirmDelete = async () => {
      if (!deleteUserId.value) return
      
      try {
        const res = await axios.delete(`/api/admin/users/${deleteUserId.value}`)
        if (res.data.success) {
          ElMessage.success('用户已删除')
          fetchUsers()
          deleteDialogVisible.value = false
        } else {
          ElMessage.error(res.data.message || '删除失败')
        }
      } catch (error) {
        console.error('删除用户失败:', error)
        ElMessage.error('删除用户失败')
      }
    }
    
    const getCreditScoreColor = (score) => {
      if (score >= 80) return '#67C23A'
      if (score >= 60) return '#E6A23C'
      return '#F56C6C'
    }
    
    onMounted(() => {
      fetchUsers()
    })
    
    return {
      loading,
      users,
      filteredUsers,
      searchQuery,
      editDialogVisible,
      deleteDialogVisible,
      editForm,
      handleSearch,
      handleEdit,
      handleStatusChange,
      handleDelete,
      submitEdit,
      confirmDelete,
      getCreditScoreColor
    }
  }
}
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  width: 300px;
}

.delete-confirm {
  text-align: center;
  margin: 20px 0;
}
</style> 